package com.phpxiu.app.utils;


import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.os.StatFs;
import android.util.Log;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.ImageRequestBuilder;
import com.phpxiu.app.api.callback.BlurPicPostProcessor;
import com.phpxiu.app.view.custom.FrescoImageView;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @file
 * @brief 自定义工具类
 * @author 吴金洲
 * @note 自定义扩展工具方法
 *
 */
public class KKYUtil {

    public final static boolean DEBUG=false;

    public final static String KKY="KKYLog";

    private final static SimpleDateFormat FORMAT_Y_M_D=new SimpleDateFormat("yyyy-MM-dd");

    private final static SimpleDateFormat DATE_FORMAT=new SimpleDateFormat();

    private final static long SECOND=1000;//秒

    private final static long MINUTE=60*SECOND;//分

    private final static long HOUR=60*MINUTE;//时

    private final static long DAY=24*HOUR;//天

    /**
     * 日志输出
     */
    public static void log(String TAG,String msg){
        if(DEBUG){
            Log.i(TAG, msg);
        }
    }

    /**
     * 日志输出
     */
    public static void log(String msg){
        if(DEBUG){
            Log.i(KKY, msg);
        }
    }

    /**
     * 手机号码规范验证
     */
    public static boolean isMobileNo(String phoneNum) {
        String telRegex="[1][358]\\d{9}";
        Pattern p = Pattern
                .compile(telRegex);
        Matcher m = p.matcher(phoneNum);
        return m.matches();
    }

    /**
     * MD5加密码处理
     */
    public  static String Str2MD5(String info){
        try{
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(info.getBytes("UTF-8"));
            byte[] encryption = md5.digest();
            StringBuffer strBuf = new StringBuffer();
            for (int i = 0; i < encryption.length; i++){
                if (Integer.toHexString(0xff & encryption[i]).length() == 1){
                    strBuf.append("0").append(Integer.toHexString(0xff & encryption[i]));
                } else {
                    strBuf.append(Integer.toHexString(0xff & encryption[i]));
                }
            }
            return strBuf.toString();
        }catch (NoSuchAlgorithmException e){
            return null;
        }catch (UnsupportedEncodingException e){
            return null;
        }
    }



    /**
     * 取得当前时间年月日格式的日期字串
     */
    public static String getCurrentDateYMD(){
        return dateFormatYMD(new Date());
    }


    /**
     * 取得某日期年月日格式的日期字串
     */
    public static String dateFormatYMD(Date date){
        return FORMAT_Y_M_D.format(date);
    }

    /**
     * 根据起始时间算距离当前预览时间
     * @return
     */
    public static String timeDistanceFromStart(long start,String ymdPattern,String day,String h,String minute,String defaultStr){
        long distance=System.currentTimeMillis()-start;
        long minuteCount=distance/MINUTE;//多少分钟
        int hourCount=(int)(distance/HOUR);
        int dayCount=(int)(distance/DAY);
        if(minuteCount>=1&&minuteCount<60){
            return minuteCount+minute;
        }else if(hourCount>=1&&hourCount<24) {
            return hourCount+h;
        }else if(dayCount>=1&&dayCount<30) {
            return dayCount+day;
        }else if(dayCount>30) {
            DATE_FORMAT.applyPattern(ymdPattern);
            return DATE_FORMAT.format(start);
        }
        return defaultStr;
    }

    /**
     * 根据时长算距离当前预览时间
     * @return
     */
    public static String timeDistance(long distance,String ymdPattern,String day,String h,String minute,String defaultStr){
        distance=distance*SECOND;//多少秒
        long minuteCount=distance/MINUTE;//多少分钟
        int hourCount=(int)(distance/HOUR);
        int dayCount=(int)(distance/DAY);
        if(minuteCount>=1&&minuteCount<60){
            return minuteCount+" "+minute;
        }else if(hourCount>=1&&hourCount<24) {
            return hourCount+" "+h;
        }else if(dayCount>=1&&dayCount<30) {
            return dayCount+" "+day;
        }else if(dayCount>=30) {
            DATE_FORMAT.applyPattern(ymdPattern);
            long now=System.currentTimeMillis();
            long start=now-distance;
            return DATE_FORMAT.format(start);
        }
        return defaultStr;
    }

    /**
     * long值转换成时分秒格式表示的长度
     * @param duration 时间长度值long或int
     */
    public static String dateFormatHMS(long duration,String hourSplit,String minuteSplit,String secondSplit){
        int hour=(int)(duration/HOUR);//计算小时
        int minute=(int)((duration-hour*HOUR)/MINUTE);//计算分钟
        int second=(int)((duration-hour*HOUR-minute*MINUTE)/SECOND);//计算秒
        String h="00";
        String m="00";
        String s="00";
        if(hour<10){
            h="0"+hour;
        }else{
            h=""+hour;
        }
        if(minute<10){
            m="0"+minute;
        }else{
            m=""+minute;
        }
        if(second<10){
            s="0"+second;
        }else{
            s=""+second;
        }
        return h+hourSplit+m+minuteSplit+s+secondSplit;
    }

    /**
     * 根据 drawable获取Bitmap
     * @param context
     * @param drawable
     * @return
     */
    public static Bitmap getBitmapByDrawable(Context context,int drawable){
        return BitmapFactory.decodeResource(context.getResources(), drawable);
    }

    /**
     * 根据 drawable获取指定宽高的Bitmap
     * @param context
     * @param drawable
     * @param width
     * @param height
     * @return
     */
    public static Bitmap getBitmapByDrawable(Context context,int drawable,int width,int height){
        Bitmap bitmap=getBitmapByDrawable(context,drawable);
        Bitmap newBitmap=Bitmap.createScaledBitmap(bitmap,width,height,true);
        if(bitmap!=newBitmap) {
            bitmap.recycle();
        }
        return newBitmap;
    }

    /**************************************************尺寸换算及取值**************************************/

    /**
     * 获得屏幕px单位高度
     */
    public static final float getHeightInPx(Context context) {
        final float height = context.getResources().getDisplayMetrics().heightPixels;
        return height;
    }

    /**
     * 获得屏幕px单位宽度
     */
    public static final float getWidthInPx(Context context) {
        final float width = context.getResources().getDisplayMetrics().widthPixels;
        return width;
    }

    /**
     * 获得屏幕dp单位高度
     */
    public static final int getHeightInDp(Context context) {
        final float height = context.getResources().getDisplayMetrics().heightPixels;
        int heightInDp = px2dip(context, height);
        return heightInDp;
    }
    /**
     * 获得屏幕dp单位宽度
     */
    public static final int getWidthInDp(Context context) {
        final float height = context.getResources().getDisplayMetrics().heightPixels;
        int widthInDp = px2dip(context, height);
        return widthInDp;
    }

    /**
     * dp转px值
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * px转dp值
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * px转sp值
     */
    public static int px2sp(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * sp转px值
     */
    public static int sp2px(Context context, float spValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (spValue * scale + 0.5f);
    }

    /**
     * dp转px值
     */
    public static float dp2px(Resources resources, float dp) {
        final float scale = resources.getDisplayMetrics().density;
        return  dp * scale + 0.5f;
    }

    /**
     * sp转px值
     */
    public static float sp2px(Resources resources, float sp){
        final float scale = resources.getDisplayMetrics().scaledDensity;
        return sp * scale;
    }

    /****************************************************************图片高斯模糊*************************************************************/
    /**
     * 用Fresco图片库控件，显示一张高斯模糊效果的图片
     * @param url 图片地址
     * @param imageView 显示图片的控件
     * @param radius 模糊半径
     * @param canReuseInBitmap 效果是否复用
     */
    public static void showBlurFresco(String url,FrescoImageView imageView,int radius, boolean canReuseInBitmap){
        ImageRequest request = ImageRequestBuilder.newBuilderWithSource(Uri.parse(url))
                .setPostprocessor(new BlurPicPostProcessor(radius,canReuseInBitmap))
                .build();
        DraweeController controller = Fresco.newDraweeControllerBuilder()
                .setImageRequest(request)
                .setOldController(imageView.getController())
                .build();
        imageView.setController(controller);
    }



    /**************************************检测SD卡信息**********************************************************************************************/
    /**
     * 检测SD卡是否存在
     */
    public static boolean hasSD() {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            return true;
        }else{
            return false;
        }
    }
    /**
     * 检测SD卡空余空间是否足够
     */
    public static boolean enoughSD(int size){
        if(getSDFreeSize()<size){
            return false;
        }
        return true;
    }

    /**
     * 检测SD卡空余空间(MB)
     */
    public static long getSDFreeSize(){
        //取得SD卡文件路径
        File path = Environment.getExternalStorageDirectory();
        StatFs sf = new StatFs(path.getPath());
        //获取单个数据块的大小(Byte)
        long blockSize = sf.getBlockSize();
        //空闲的数据块的数量
        long freeBlocks = sf.getAvailableBlocks();
        return (freeBlocks * blockSize)/1024 /1024; //单位MB
    }

}
